package com.lh.runmanage.unit;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tool.RedisAction;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 梁昊
 * @date 2019/12/3
 * @function
 * @editLog
 */
@Component
public class RedisOperator {
    @Autowired
    RedisAction redisAction;

    /**
     * 生成用户AccessToken
     *
     * @param keyName        用户ID
     * @param expirationTime token有效期，默认1天
     * @param isAutoAgain    是否自动续期
     * @return
     */
    public String writeIntoToken(String keyName, long expirationTime, boolean isAutoAgain) {
        try {
            String accessToken = redisAction.getValue(keyName);
            if (accessToken == null) {
                accessToken = UUID.randomUUID().toString().replace("-", "");
                isAutoAgain = true;
            }
            if (isAutoAgain) {
                redisAction.saveKeyAndValue(keyName, accessToken, expirationTime, TimeUnit.DAYS);
            }
            return accessToken;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 得到、写入项目Token
     * @param projectId 项目ID
     * @return 项目token
     */
    public String writeProjectToken(String projectId){
        String accessToken = UUID.randomUUID().toString().replace("-", "");
        redisAction.saveKeyAndValue(accessToken, projectId);
        return accessToken;
    }

    public void deleteProjectToken(String projectToken){
        redisAction.delete(projectToken);
    }
}
